package com.tanhua.server.service;


import com.tanhua.domain.db.*;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.db.*;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TestSoulService {

    @DubboReference
    private SoulTestApi soulTestApi;
    @DubboReference
    private QuestionnaireApi questionnaireApi;
    @DubboReference
    private QuestionTextApi questionTextApi;
    @DubboReference
    private SoulOptionsApi soulOptionsApi;
    @DubboReference
    private SoulUserLockApi soulUserLockApi;
    @DubboReference
    private SoulReportApi soulReportApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private  UserInfoApi userInfoApi;

    private String prefix="report_id_";


    /**
     * 问卷列表
     * @return
     */
    public ResponseEntity queryQuestionList(){

        //返回结果的list集合---TestSoulVo对象
        List<TestSoulVo> testSoulVoList =new ArrayList<>();

        TestSoulVo testSoulVo=null;
        //查找试卷
        List<SoulQuestionnaire> questionnaireList=questionnaireApi.queryQuestionnaire();
        //遍历试卷
        for (SoulQuestionnaire soulQuestionnaire : questionnaireList) {
            //创建testSoul对象
            testSoulVo = new TestSoulVo();

            testSoulVo.setId(soulQuestionnaire.getId().toString());//试卷id
            testSoulVo.setName(soulQuestionnaire.getName());//试卷名称
            testSoulVo.setCover(soulQuestionnaire.getCover());//试卷图片
            testSoulVo.setLevel(soulQuestionnaire.getLevel().toString());//试卷等级
            testSoulVo.setStar(soulQuestionnaire.getStar());//试卷星级

            //查题目----试卷题目
            List<SoulQuestionVo> questionVoList = queryQuestion(soulQuestionnaire.getId().toString());
            testSoulVo.setQuestions(questionVoList);

            //查是否锁住 ----试卷锁
            SoulUserLock soulUserLock = soulUserLockApi.findByUserIdAndQuestionnaireId(UserHolder.getUserId().toString(), soulQuestionnaire.getId().toString());
            testSoulVo.setIsLock(soulUserLock.getIsLock());

            String value = redisTemplate.boundValueOps(prefix + UserHolder.getUserId()+soulQuestionnaire.getId()).get();
            if (value==null){
                testSoulVo.setReportId(null);
            }else{
                testSoulVo.setReportId(value);
            }


            //往集合中添加
            testSoulVoList.add(testSoulVo);
        }
        return ResponseEntity.ok(testSoulVoList);

    }

    //查题目的方法
    public List<SoulQuestionVo> queryQuestion(String questionnaireId){
        //按照书卷id 查每套试卷的题目
        List<SoulQuestion> questionList=questionTextApi.queryQuestion(questionnaireId);

        List<SoulQuestionVo> questionVoList =new ArrayList<>();
        for (SoulQuestion soulQuestion : questionList) {
            SoulQuestionVo soulQuestionVo = new SoulQuestionVo();

            soulQuestionVo.setQuestion(soulQuestion.getQuestion());//试卷问题
            //查选项
            List<SoulOptionsVo> optionsVoList = queryOptionVo(soulQuestion.getId().toString());
            soulQuestionVo.setId(soulQuestion.getId().toString());
            soulQuestionVo.setOptions(optionsVoList);//试卷选项

            questionVoList.add(soulQuestionVo);
        }
        return questionVoList;

    }

    //查选项方法
    public List<SoulOptionsVo> queryOptionVo(String questionId){
        //根据问题id查选项
        List<SoulOptions> optionsList=soulOptionsApi.queryOptions(questionId);

        List<SoulOptionsVo> optionsVoList =new ArrayList<>();
        for (SoulOptions soulOptions : optionsList) {
            SoulOptionsVo soulOptionsVo = new SoulOptionsVo();
            soulOptionsVo.setId(soulOptions.getId().toString());//选项id
            soulOptionsVo.setOption(soulOptions.getContent());//选项文本

            optionsVoList.add(soulOptionsVo);
        }
        return optionsVoList;
    }










    /**
     * 提交列表
     * @param soulAnswerList
     * @return
     */
    public ResponseEntity saveAnswer(List<SoulAnswer> soulAnswerList){
        //算出得分，
        Integer num=0;
        for (SoulAnswer soulAnswer : soulAnswerList) {
            String questionId = soulAnswer.getQuestionId();
            String optionId = soulAnswer.getOptionId();
            String score=soulOptionsApi.queryScore(questionId,optionId);
            num=num+Integer.parseInt(score);
        }
        //在报告表中查出报告id--需要卷子id
        SoulAnswer soulAnswer = soulAnswerList.get(0);
        String questionnaireId=questionTextApi.queryQuestionnaireId(soulAnswer.getQuestionId());

        String score =num.toString();
        SoulReport soulReport = soulReportApi.queryReport(questionnaireId, score);
        String reportId = soulReport.getId().toString();

        //更改lock状态--解锁
        updateIsLock(questionnaireId,UserHolder.getUserId().toString());
        //插入数据
        insertSoulTest(questionnaireId,soulReport.getId().toString(),UserHolder.getUserId().toString(), score);

        //向redis中添加记录
        redisTemplate.boundValueOps(prefix+UserHolder.getUserId()+questionnaireId).set(reportId);

        return ResponseEntity.ok(reportId);
    }


    //更改 lock 的状态
    public void updateIsLock(String questionnaireId,String userId){
        int i = Integer.parseInt(questionnaireId);

        SoulUserLock soulUserLock = new SoulUserLock();
        if (i==1){
            SoulUserLock userLock = soulUserLockApi.findByUserIdAndQuestionnaireId(userId, Integer.toString(2));
            soulUserLock.setId(userLock.getId());//id
        }else if (i==2){
            SoulUserLock userLock = soulUserLockApi.findByUserIdAndQuestionnaireId(userId, Integer.toString(3));
            soulUserLock.setId(userLock.getId());
        }
        soulUserLock.setIsLock(0);//isLock 锁
        soulUserLock.setUpdated(new Date());//updated更新时间

        soulUserLockApi.update(soulUserLock);
    }

    //插入数据-----保存记录
    public void insertSoulTest(String questionnaireId,String reportId,String userId,String score){

        SoulTest soulTest = new SoulTest();
        soulTest.setUserId(userId);
        soulTest.setQuestionnaireId(questionnaireId);
        SoulQuestionnaire soulQuestionnaire=questionnaireApi.queryById(Integer.parseInt(questionnaireId));
        soulTest.setName(soulQuestionnaire.getName());
        soulTest.setStar(soulQuestionnaire.getStar());
        soulTest.setScore(score);
        soulTest.setReportId(reportId);
        soulTest.setUpdated(new Date());

        SoulTest soulTest1=soulTestApi.findByUserIdAndQuestionnaireId(userId,questionnaireId);
        if (soulTest1==null){
            soulTest.setCreated(new Date());
            soulTestApi.save(soulTest);
        }else{
            soulTest.setId(soulTest1.getId());
            soulTestApi.update(soulTest);
        }



    }










    //测灵魂-查看结果（学生实战）
    public ResponseEntity queryResult(String reportId){

        SoulReport soulReport = soulReportApi.queryResult(Integer.parseInt(reportId));
        SoulReportVo soulReportVo = new SoulReportVo();

        soulReportVo.setConclusion(soulReport.getContent());
        soulReportVo.setCover(soulReport.getCover());

        List<Map<String,Object>> dimensionsList =new ArrayList<>();
        String[] keys={"外向","抽象","理性","判断"};
        for (String key : keys) {
            Map<String,Object> map =new HashMap();
            map.put("key",key);
            map.put("value",RandomStringUtils.randomNumeric(2)+"%");
            dimensionsList.add(map);
        }
        soulReportVo.setDimensions(dimensionsList);



        List<UserInfo> similarYouList=new ArrayList<>();

        List<SoulTest> soulTestList = soulTestApi.findByReportId(reportId);
        if (soulTestList.size()==0||soulTestList==null){
            for (int i = 0; i < 10; i++) {
                long l = Integer.toUnsignedLong(i);
                UserInfo userInfo = userInfoApi.findById(l);
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setId(userInfo.getId());
                userInfo1.setAvatar(userInfo.getAvatar());
                similarYouList.add(userInfo1);
            }
        }else{

            for (SoulTest soulTest : soulTestList) {
                UserInfo userInfo = userInfoApi.findById(Long.parseLong(soulTest.getUserId()));
                if (userInfo.getId()==UserHolder.getUserId()){
                    continue;
                }
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setId(userInfo.getId());
                userInfo1.setAvatar(userInfo.getAvatar());
                similarYouList.add(userInfo1);
            }
        }

        soulReportVo.setSimilarYou(similarYouList);

        return  ResponseEntity.ok(soulReportVo);
    }








}
